#include "./app_fan.h"
#include "./app_adc.h"
#include "./app_device.h"

struct fan_dev_t *fanner;

#ifdef APP_FAN_TEST
uint8_t val = 0;
	int i = 0;
static void fan_delay(void)
{

	for(i=0;i<0xffff;i++);
}
static void fan_test(void)
{
	while(1)
	{
fanner->set_speed(fanner,val);
	if(val>100)val=0;
	else val++;
	fan_delay();	
	}
}
#endif
 /**
  * @brief 比较 当前电流值和前一次电流值大小
  * 
  * @param iout  当前电流值
  * @param pre_iout  前一次电流值
  * @return uint8_t 两个值相等返回 0xff 当前电流大时返回 1, 前一次电流值大时返回0 
  */
// static uint8_t max_iout(uint16_t iout,uint16_t pre_iout)
// {      
//        if(iout == pre_iout)return 0xff;
//        else if(iout > pre_iout)return 1;
//        else return 0;
// }
void app_fan_init(void)
{
    fan_init(&fanner);   
	#ifdef APP_FAN_TEST
		fan_test();
	#endif
}
uint8_t fan_sw = 0;
uint8_t fan_count = 0;
float pre_Volout=0;
uint8_t pwmtmp = 0;

void app_fan_speed_handler(struct fan_dev_t *dev)
{
	 pwmtmp = dev->get_speed();
   if((mod_device->get_dev_state(mod_device))==1)
	 {
					dev->enable();
					
					if(pre_Volout > VolIout)//电流变小
					{
							fan_sw = 1; //电流减小
					}
					else if(pre_Volout < VolIout)//电流变大
					{ 
							pwmtmp++;
							dev->set_speed(dev,pwmtmp);
					}
					else
					{
							//fan_sw = 0; //
					}

					if(fan_sw == 1)
					{
							fan_count=get_global_timer();
							fan_sw = 2;
					}
					else if(fan_sw == 2)
					{
							if((fan_count+10)==get_global_timer())
							{
									fan_sw=3;
							}
					}
					else if(fan_sw == 3)
					{
							pwmtmp--;
							if(pwmtmp<=20)pwmtmp=20;
							dev->set_speed(dev,pwmtmp);
						  /*
								减小到什么程度
						   */
					}
				pre_Volout = VolIout;	 
	 }
	 else
	 {
		dev->disable();
		dev->set_speed(dev,pwmtmp);
	 }
    
}
void app_fan_lopp_func(void)
{
    app_fan_speed_handler(fanner);  
}

